var express = require('express');
var router = express.Router();
const mongodb = require('./mongodb.js');
const crypto=require('crypto');
const logs = require('./logs.js');
const utils = require('./utils.js');
var fs = require('fs');
var ffmpeg = require('fluent-ffmpeg');
const path = require('path');
const videoStream = require('video-stream');

var cookie = {};
var union_progress = {};

function fluent_test() {
	logs.logvar('fluent_test');

	ffmpeg('./routes/video/test.mp4')
	.outputOptions(['-y', '-r 24', '-pix_fmt yuvj420p', '-profile:v baseline'])
	.on('start', function(commandLine) {
		logs.logvar('Spawned Ffmpeg with command: ' + commandLine);
	}).on('stderr', function(stderrLine) {
		logs.logvar('Stderr output: ' + stderrLine);
	}).on('progress', function(progress) {
		logs.logvar('Processing: ' + progress.percent + '% done');
	}).on('end', function() {
		logs.logvar('Processing finished !');
	})
	.complexFilter([
		// Rescale input stream into stream 'rescaled'
		'[0:v]crop=360:360:0:0,scale=720*720[output1]',
		'[0:v]crop=360:360:360:0,scale=720*720[output2]'
	])
	.outputOptions(['-map [output1]', './routes/video/1.mp4', '-map [output2]'])
	.addOutput('./routes/video/2.mp4')
	.run();

	return;

	ffmpeg('./routes/video/test.mp4')
	.outputOptions('-y')
	.outputOptions('-r 24')
	.outputOptions('-pix_fmt yuvj420p')
	.outputOptions('-profile:v baseline')
	.complexFilter([
		// Rescale input stream into stream 'rescaled'
		'[0:v]crop=360:360:0:0,scale=720*720[output1]',
		'[0:v]crop=360:360:360:0,scale=720*720[output2]'
	], ['output1', 'output2'])
	.on('start', function(commandLine) {
		logs.logvar('Spawned Ffmpeg with command: ' + commandLine);
	}).on('stderr', function(stderrLine) {
		console.log('Stderr output: ' + stderrLine);
	}).on('progress', function(progress) {
		console.log('Processing: ' + progress.percent + '% done');
	}).on('end', function() {
		console.log('Processing finished !');
	}).save('./routes/video/output888.mp4');
}


//fluent_test();
function video_probe(file){
	return new Promise(async function(resolve, reject) {
		ffmpeg()
		.input(file)
		.ffprobe(0, function(err, data) {
			if(err){
				reject(err);
			}else{
				resolve(data);
			}
		});
	})
}

async function video_division(user, file, n_x, n_y, callback){
	const video_file = `${utils.userPath(user)}/${file}`;
	const video_path = `${utils.userPath(user)}/output/${file}`;

	logs.logvar(video_file, video_path);
	utils.mkdirsSync(video_path);

	const probe = await video_probe(video_file);
	const video = probe.streams.filter(it=>{return it.codec_type == 'video'})[0];
	const nb_frames = video.nb_frames;

	var crops = [];
	var options = [];

	const width = video.width;
	const height = video.height;
	const per_width = Math.floor(width/n_x);
	const per_height = Math.floor(height/n_y);

	logs.logvar(probe, nb_frames, width, height, n_x, n_y, file, video_path);

	for(let j = 0; j < n_y; j++){
		for(let i = 0; i < n_x; i++) {
			const x = i * per_width;
			const y = j * per_height;
			const name = j + '.' + i;
			const crop = `[0:v]crop=${per_width}:${per_height}:${x}:${y},scale=720*720[${name}]`;
			crops.push(crop);
			options.push(`-map [${name}]`);
			options.push(`${video_path}/${name}.mp4`);
		}
	}

	//logs.logvar(crops, options);
	//logs.logvar(options.slice(0, -1));
	//logs.logvar(options[options.length-1]);
	//return;

	ffmpeg(video_file)
	.outputOptions(['-y', '-r 24', '-pix_fmt yuvj420p', '-profile:v baseline'])
	.on('start', function(commandLine) {
		logs.logvar('Spawned Ffmpeg with command: ' + commandLine);
	}).on('stderr', function(stderrLine) {
		//logs.logvar('Stderr output: ' + stderrLine);
	}).on('progress', function(progress) {
		logs.logvar('Processing: ' + JSON.stringify(progress) + '% done');
		if(typeof (callback) == 'function'){
			callback('progress', progress);
		}
	}).on('end', function() {
		logs.logvar('Processing finished !');
		if(typeof (callback) == 'string'){
			callback('end');
		}
	})
	.complexFilter(crops)
	.outputOptions(options.slice(0, -1))
	.addOutput(options[options.length-1])
	.run();
}

//video_division('a@a.com','test.mp4', 2, 2, );

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.post('/register', async function(req, res, next){
	try{
		//logs.logvar(req);
		logs.logvar(req.body);
		const ret = await mongodb.insert(req.body);
		logs.logvar(req.body, ret);

		res.send({result: 'ok', error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e});
	}
});

router.post('/login', async function(req, res, next){
	try{
		//logs.logvar(req);
		const ret = await mongodb.login(req.body);
		logs.logvar(ret);

		res.send({result: ret, error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

router.post('/msg', async function(req, res, next){
	try{
		//logs.logvar(req);
		logs.logvar(req.cookies);

		return res.send({result: 'ok', error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

router.post('/search', async function(req, res, next){
	try{
		//logs.logvar(req);
		const ret = await mongodb.search(req.body);
		logs.logvar(ret);

		return res.send({result: ret, error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

/**********
 * 注册设备
 */
router.post('/add', async function(req, res, next){
	try{
		//logs.logvar(req);
		await mongodb.add(req.body);
		res.send({result: 'ok', error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

router.post('/add_devices', async function(req, res, next){
	try{
		//logs.logvar(req);
		await mongodb.add_device(req.body);
		res.send({result: 'ok', error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

router.post('/del_devices', async function(req, res, next){
	try{
		//logs.logvar(req);
		await mongodb.del_device(req.body);
		res.send({result: 'ok', error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

router.post('/union', async function(req, res, next){
	try{
		var time = new Date().getTime();
		while(union_progress[time] != null){
			time++;
			logs.logvar(req.body, time);
		}

		logs.logvar(req.body, time);
		//await mongodb.login(req.body);

		await video_division(req.body.id, req.body.file, req.body.n_x, req.body.n_y, function (type, progress) {
			union_progress[time] = progress;
			logs.logvar(progress, time);
		});
		res.send({result: time, error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

router.post('/union_progress', async function(req, res, next){
	try{
		logs.logvar(req.body, union_progress);
		res.send({result: union_progress[req.body.progress], error: null});
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

module.exports = router;



